﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Lead2012.Business;
using Lead2012.Models;
using Lead2012.ViewModels;
using Lead2012.Repository;
using Lead2012.Utility;
using System.Web.Security;

namespace Lead2012.Controllers
{
    public class UserController : BaseController
    {
        EFRoleProvider provider = new EFRoleProvider();
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // Create an instance of repository
        UserManagementRepository umRepository = new UserManagementRepository();

        [Authorize(Roles = "Administrator")]
        public ActionResult Index()
        {
            UserViewModel model = new UserViewModel();

            // Setup model
            model.PageType = "Menu";
            SetupCommon(model, string.Empty, "FirstName");
            umRepository.GetModel(model, string.Empty, string.Empty, string.Empty, 1, 10);
           
            return View(model);
        }

        public ActionResult Filters(string keywords, string sortBy, string sortOrder, int pageIndex, int pageSize)
        {
            UserViewModel model = new UserViewModel();

            // Setup model
            if (pageSize == 0)
                pageSize = 10;
            if (pageIndex == 0)
                pageIndex = 1;

            umRepository.GetModel(model, keywords, sortBy, sortOrder, pageIndex, pageSize);

            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Delete(int id)
        {
            UserRepository repository = new UserRepository();
            UserViewModel model = new UserViewModel();

            // Delete action
            repository.Delete(id);

            // Setup model
            umRepository.GetModel(model, string.Empty, string.Empty, string.Empty, 1, 10);
            
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Add()
        {
            UserViewModel model = new UserViewModel();

            // Setup model
            model.PageType = "Menu";
            SetupCommon(model, string.Empty, "FirstName");
            umRepository.GetModel(model, 0);

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(FormCollection form)
        {
            User model = new User();
            model.FirstName = form["FirstName"].ToString();
            model.LastName = form["LastName"].ToString();
            model.Fullname = string.Format("{0} {1}", model.FirstName, model.LastName);
            model.Email = form["Email"].ToString();
            model.Password = EncryptionData.Encryption(form["Password"].ToString());
            model.IsLockedOut = (form["IsLockedOut"] != null && form["IsLockedOut"].ToString() == "on") ? true : false;
            
            // Attempt to register the user
            MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Email, model.Password, model.Email);

            if (createStatus == MembershipCreateStatus.Success)
            {
                // Assign role
                provider.AddUserToRole(model.Email, "Registered");

                // Send an email to User
                UserRepository umRepository = new UserRepository();
                var userModel = umRepository.GetSingle(model.Email);

                // Update Users
                userModel.Fullname = model.Fullname;
                userModel.FirstName = model.FirstName;
                userModel.LastName = model.LastName;
                userModel.IsLockedOut = model.IsLockedOut;
                userModel.GUID = Guid.NewGuid().ToString();
                umRepository.Save(userModel);
            }
            else
            {
                ViewBag.ErrorMessage = "Địa chỉ email đã tồn tại.";
                return View();
            }

            return Redirect("/User");
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(int id)
        {
            UserViewModel model = new UserViewModel();

            // Setup model
            model.PageType = "Menu";
            SetupCommon(model, string.Empty, "FirstName");
            umRepository.GetModel(model, id);
            ViewBag.UserId = id;

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, FormCollection form)
        {
            UserRepository repository = new UserRepository();
            User model = new User();
            model = repository.GetSingle(id);

            model.FirstName = form["FirstName"].ToString();
            model.LastName = form["LastName"].ToString();
            model.Fullname = string.Format("{0} {1}", model.FirstName, model.LastName);
            model.Email = form["Email"].ToString();
            if (!string.IsNullOrEmpty(form["Password"].ToString()))
                model.Password = EncryptionData.Encryption(form["Password"].ToString());

            if (!provider.IsUserInRoleExtend(model.Email, "Administrator"))
            {
                model.IsLockedOut = (form["IsLockedOut"] != null && form["IsLockedOut"].ToString() == "on") ? true : false;
            }

            repository.Save(model);

            return Redirect("/User");
        }
     }
}